import { ref } from 'vue'
import store from '@/store'
import { defineStore } from 'pinia'
import { usePermissionStoreHook } from './permission'
import {
  getToken,
  removeToken,
  setToken,
  getUserName,
  removeUserName,
  setUserName,
  getPhone,
  removePhone,
  setPhone,
  setRole,
  removeRole
} from '@/utils/cache/cookies'
import { resetRouter } from '@/router'
import { loginApi } from '@/api/login'
import { type LoginRequestData, type LoginResponseData } from '@/api/login/types/login'
import { RoleType } from '@/types/enum'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string>(getToken() || '')
    const realname = ref<string>(getUserName() || '')
    const realphone = ref<string>(getPhone() || '')
    const role = ref<RoleType>(RoleType.Nomal)
    const permissionStore = usePermissionStoreHook()
    /** 设置角色*/
    const setRoles = (value: RoleType) => {
      role.value = value
    }
    /** 获取角色*/
    const getRoles = () => {
      return role.value
    }
    /** 登录 */
    const login = async ({ phone, code }: LoginRequestData) => {
      const { data } = await loginApi({ phone, code })
      setToken(data.token)
      setUserName(data.info.name)
      setPhone(data.info.phone)
      setRole(data.info.role)
      token.value = data.token
      realname.value = data.info.name
      realphone.value = data.info.phone
      role.value = data.info.role
    }

    /** 微信登录 */
    const wxLogin = async (data: LoginResponseData) => {
      setToken(data.token)
      setUserName(data.info.name)
      setPhone(data.info.phone)
      setRole(data.info.role)
      token.value = data.token
      realname.value = data.info.name
      realphone.value = data.info.phone
      role.value = data.info.role
    }

    /** 登出 */
    const logout = async () => {
      removeToken()
      removePhone()
      removeUserName()
      removeRole()
      permissionStore.isDynamicRoutesAdded = false
      token.value = ''
      realname.value = ''
      realphone.value = ''
      role.value = RoleType.Nothing
      resetRouter()
    }
    /** 重置 Token */
    const resetToken = () => {
      removeToken()
      token.value = ''
      role.value = RoleType.Nothing
    }
    /** 重置 Visited Views 和 Cached Views */
    // const _resetTagsView = () => {
    //   tabStore.delAllVisitedViews()
    //   tabStore.delAllCachedViews()
    // }

    return {
      token,
      realname,
      realphone,
      setRoles,
      getRoles,
      role,
      login,
      wxLogin,
      logout,
      resetToken
    }
  },
  {
    persist: true
  }
)

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
